package lendingbooks.android;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lendingbooks.GlobalState;
import lendingbooks.android.book.Book;
import lendingbooks.android.book.IsbnSearchError;
import lendingbooks.utils.ServiceCallException;
import lendingbooks.utils.ServiceManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import user.User;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.google.gson.Gson;

public class LendingBooksActivity extends Activity {



	private Facebook facebookAPI = new Facebook("141686359258739");
	private EditText isbnEditText;
	private Button scan;
	private Button search;
	private Button facebook;
	private Button myLibrary;
	
	private TextView menssage;
	private TextView userText;
	private GlobalState gs;
	private ServiceManager sm = new ServiceManager();
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		//Debug.startMethodTracing();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		gs = (GlobalState)getApplicationContext();
		search = (Button) findViewById(R.id.search);              
		scan = (Button) findViewById(R.id.scan);
		isbnEditText = (EditText) findViewById(R.id.isbn);
		userText = (TextView) findViewById(R.id.user);
		facebook = (Button) findViewById(R.id.facebookButton);
		menssage = (TextView) findViewById(R.id.menssage);			
		myLibrary = (Button) findViewById(R.id.myLibrary);		
		serviceLoginFacebook();
		
		
		search.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {				
				String isbn = (String)isbnEditText.getText().toString();				
				_BuscarIsbn(isbn);				
			}
		});

		scan.setOnClickListener( new OnClickListener() {			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				intent.setPackage("com.google.zxing.client.android");
				startActivityForResult(intent, 0);				
			}
		});

		facebook.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				_FacebookAuth();
			}
		});
		
		myLibrary.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				Intent myLibraryIntent = new Intent(v.getContext(), MyLibraryActivity.class);
				startActivity(myLibraryIntent);				
			}
		});
		
	}
	public void _FacebookAuth(){    	
		facebookAPI.authorize(this, new DialogListener() {			
			@Override
			public void onFacebookError(FacebookError e) {				
			}
			@Override
			public void onError(DialogError e) {
			}
			@Override
			public void onCancel() {
			}
			@Override
			public void onComplete(Bundle values) {
			}		
		});
	}


	public void onActivityResult(int requestCode, int resultCode, Intent intend){
		if(requestCode==0){
			if(resultCode==RESULT_OK){
				String contents = intend.getStringExtra("SCAN_RESULT");
				isbnEditText.setText(contents);
				_BuscarIsbn(contents);
			}    	
		}else{			
			//menssage.setText("onActivityResult_"+requestCode+"_"+resultCode+"_"+facebookAPI.isSessionValid());			
			facebookAPI.authorizeCallback(requestCode, resultCode, intend);
			JSONObject json;
			try {
				if(facebookAPI.isSessionValid()){					
				String sMe = facebookAPI.request("me");
				json = Util.parseJson(sMe);		
				String name = json.getString("name");
				String id = json.getString("id");
				gs.setUserFacebookId(id);							
				gs.setUserName(name);
				serviceLoginFacebook();							
				}else{
					menssage.setText("NO USER");
				}
			} catch (JSONException e) {
				e.printStackTrace();			
			} catch (FacebookError e) {
				// TODO Auto-generated catch block
				e.printStackTrace();							
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}     			
		}     		
	}
	
	public void serviceLoginFacebook() {
		try {
		String idFacebook = gs.getUserFacebookId();
		HashMap<String , String> params = new HashMap<String, String>();
		params.put("facebookUid", idFacebook);
		String result = sm.call(ServiceManager.SERVICE.LOGIN_FACEBOOK, params);		
		Gson gson = new Gson();
		User user = gson.fromJson(result, User.class);
		gs.setUserId(user.getId());
		userText.setText("["+gs.getUserId()+"]"+gs.getUserName()+" FB["+gs.getUserFacebookId()+"]");
		} catch (ServiceCallException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
		    
    public void _BuscarIsbn(String p_isbn){
    	TextView bookTitleTextVier = (TextView) findViewById(R.id.bookTitle);
    	TextView bookIsbnTextVier = (TextView) findViewById(R.id.bookIsbnTextView);    	   
    	try {    		
    		HashMap<String,String> params = new HashMap<String,String>();
    		params.put("isbn", p_isbn);    		
    		
    		String responseText = sm.call(ServiceManager.SERVICE.SEARCH_BY_ISBN, params);
    		Gson gson = new Gson();
    		if(responseText.startsWith("{KO")){
    			IsbnSearchError error = gson.fromJson(responseText, IsbnSearchError.class);
    			menssage.setText("ERROR: "+error.KO);
    		} else{
    			Book book =	gson.fromJson(responseText, Book.class);
    			bookTitleTextVier.setText( book.title);
    			bookIsbnTextVier.setText(book.isbn);   
    			menssage.setText("OK");
    		}
    	} catch (Exception e) {
    		// 
    		e.printStackTrace();
    		menssage.setText("ERROR_"+e.getMessage());
    	} 
    }
}